import ArticleItem from '@/components/ArticleItem'
import { RootState } from '@/store'
import { getArticles } from '@/store/action/article'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'

type Props = {
  channel_id: number
}

export default function ArticleList({ channel_id }: Props) {
  const { activeId } = useSelector((state: RootState) => state.channel)
  const dispatch = useDispatch()
  const { articles } = useSelector((state: RootState) => state.article)
  //articles一开始没数据，要副作用完成后才有东西,所以用?.
  const list = articles[channel_id]?.list
  // console.log(111, list) //可能是undefined

  const handleRefresh = async () => {
    console.log('下拉刷新')
    await dispatch(getArticles({ channel_id, isRefresh: true }))
  }

  const [hasMore, setHasMore] = useState(true)
  const loading = useRef(false)
  const handleloadMore = async () => {
    if (loading.current) return
    loading.current = true
    // 发送请求获取更多数据，需要使用到上一次推荐的时间戳，防止获取到重复的新闻。
    try {
      await dispatch(
        getArticles({ channel_id, timestamp: articles[channel_id].timestamp })
      )
    } catch (error) {
      setHasMore(false)
    }

    loading.current = false
  }

  useEffect(() => {
    //如果list有数据，就不需要发送首次打开频道时请求
    if (list) return
    // console.log({ channel_id, activeId })
    if (channel_id === activeId) {
      console.log('发送请求获取频道数据', channel_id)
      dispatch(getArticles({ channel_id }))
    }
  }, [channel_id, activeId, dispatch, list])

  //如果还没渲染出来list则返回null
  if (!list) return null
  return (
    <div>
      {/* 下拉刷新组件 */}
      <PullToRefresh onRefresh={handleRefresh}>
        {list.map((item) => (
          <ArticleItem key={item.art_id} article={item} />
        ))}
        {/* 无限滚动 */}
        <InfiniteScroll
          hasMore={hasMore}
          loadMore={handleloadMore}
        ></InfiniteScroll>
      </PullToRefresh>
    </div>
  )
}
